from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import models
from app.db.session import get_db
from app.schemas import AlertTaskGroupCreate, AlertTaskGroupResponse
from app.core.schedule import task_manager
from typing import List

router = APIRouter()


@router.post("/groups", response_model=AlertTaskGroupResponse)
def create_task_group(task_group: AlertTaskGroupCreate, db: Session = Depends(get_db)):
    """创建预警任务组"""
    try:
        # 检查是否已存在同名任务组
        existing = db.query(models.AlertTaskGroup).filter(
            models.AlertTaskGroup.group_name == task_group.group_name
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail="任务组名称已存在")

        db_task_group = models.AlertTaskGroup(**task_group.dict())
        db.add(db_task_group)
        db.commit()
        db.refresh(db_task_group)

        # 如果任务组是启用的，添加到调度器
        if db_task_group.is_active:
            task_manager.add_task_group(db_task_group)

        return db_task_group
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建任务组失败: {str(e)}")


@router.get("/groups", response_model=List[AlertTaskGroupResponse])
def get_task_groups(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取所有任务组"""
    return db.query(models.AlertTaskGroup).offset(skip).limit(limit).all()


@router.put("/groups/{group_id}", response_model=AlertTaskGroupResponse)
def update_task_group(group_id: int, task_group: AlertTaskGroupCreate, db: Session = Depends(get_db)):
    """更新任务组"""
    db_task_group = db.query(models.AlertTaskGroup).filter(models.AlertTaskGroup.id == group_id).first()
    if not db_task_group:
        raise HTTPException(status_code=404, detail="任务组未找到")

    try:
        # 检查是否已存在同名任务组
        if db_task_group.group_name != task_group.group_name:
            existing = db.query(models.AlertTaskGroup).filter(
                models.AlertTaskGroup.group_name == task_group.group_name,
                models.AlertTaskGroup.id != group_id
            ).first()
            if existing:
                raise HTTPException(status_code=400, detail="任务组名称已存在")

        # 更新字段
        for key, value in task_group.dict().items():
            setattr(db_task_group, key, value)

        db.commit()

        # 更新调度器中的任务组
        if db_task_group.is_active:
            task_manager.add_task_group(db_task_group)  # 更新操作 = 移除旧任务 + 添加新任务
        else:
            task_manager.remove_task_group(group_id)

        return db_task_group
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新任务组失败: {str(e)}")


@router.delete("/groups/{group_id}")
def delete_task_group(group_id: int, db: Session = Depends(get_db)):
    """删除任务组"""
    db_task_group = db.query(models.AlertTaskGroup).filter(models.AlertTaskGroup.id == group_id).first()
    if not db_task_group:
        raise HTTPException(status_code=404, detail="任务组未找到")

    try:
        # 从调度器移除
        task_manager.remove_task_group(group_id)

        # 从数据库删除
        db.delete(db_task_group)
        db.commit()
        return {"message": "任务组删除成功"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除任务组失败: {str(e)}")


@router.post("/groups/{group_id}/run")
def run_task_group(group_id: int, db: Session = Depends(get_db)):
    """手动执行任务组"""
    db_task_group = db.query(models.AlertTaskGroup).filter(models.AlertTaskGroup.id == group_id).first()
    if not db_task_group:
        raise HTTPException(status_code=404, detail="任务组未找到")

    try:
        from app.core.schedule import check_task_group_rules
        check_task_group_rules(db_task_group.group_name)
        return {"message": f"任务组 {db_task_group.group_name} 已开始执行"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"执行任务组失败: {str(e)}")